package com.party.web.web.controller.crowdfundMultiple;

import com.party.common.utils.DateUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.ActivityInput;
import com.party.core.model.activity.CrowfundResources;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.EventGradation;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.web.biz.crowdfundMultiple.ActivityMultipleBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.output.activity.ActivityOutput;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author： yifeng
 * @description： 众筹项目控制器
 * @date：Created in  2017/12/20 下午 18:57
 **/
@Controller
@RequestMapping("activityMultiple/zcActivity")
public class ActivityMultipleController {

    protected static Logger logger = LoggerFactory.getLogger(ActivityMultipleController.class);
    @Value("#{party['mic.url']}")
    private String micUrl;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActivityDetailService activityDetailService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private ActivityMultipleBizService activityMultipleBizService;
    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;
    @Autowired
    private IEventGradationService eventGradationService;

    /**
     * 跳转至发布 众筹活动
     *
     * @param id
     * @return
     */
    @DataControl
    @RequestMapping(value = "publishZcAct")
    public ModelAndView publishZcAct(@ControlParam(table = "activity", column = "member", isRequired = false) String id) {
        ModelAndView mv = new ModelAndView("crowdfundMultiple/publishZcActNew");
        if (StringUtils.isNotEmpty(id)) {
            /** 活动 **/
            Activity activity = activityService.get(id);
            ActivityOutput activityOutput = ActivityOutput.transform(activity);
            activityOutput.setEditShare(activity.getEditShare());
            String address = activityService.getShowAddress(activity);
            mv.addObject("address", address);
            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
            mv.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(activity.getId(), "2");
            if (videoList.size() > 0) {
                mv.addObject("video", videoList.get(0));
            }
            mv.addObject("activity", activityOutput);

            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            mv.addObject("activityDetail", activityDetail);

            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            mv.addObject("crowdfundEvent", crowdfundEvent);

            List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(crowdfundEvent.getId());
            mv.addObject("eventGradations", eventGradations);
        } else {
            CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
            crowdfundEvent.setProgress(YesNoStatus.YES.getCode()); // 进行中
            crowdfundEvent.setCreateBy(RealmUtils.getCurrentUser().getId());
            crowdfundEvent.setCheckStatus(1);//审核通过的主题才能显示出来
            List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.list(crowdfundEvent);
            mv.addObject("crowdfundEventList", crowdfundEventList);
        }
        return mv;
    }

    /**
     * @param activity
     * @param activityDetail
     * @param result
     * @param activityInput
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 发布保存
     * @Date 9:33 2019/3/21
     **/
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = {"save"})
    public AjaxResult save(Activity activity, ActivityDetail activityDetail, BindingResult result, ActivityInput activityInput) {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            if (StringUtils.isEmpty(activity.getEventId())) {
                return AjaxResult.error("主题不能为空");
            }

            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            if (crowdfundEvent == null) {
                return AjaxResult.error("主题不能为空");
            }
            ActivityDetail detail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (detail == null) {
                return AjaxResult.error("主题详情内容不能为空");
            } else {
                activityDetailBizService.castToHTML(detail);
                activityDetail.setApplyRelated(detail.getApplyRelated());
                activityDetail.setMatchStandard(detail.getMatchStandard());
            }

            activityMultipleBizService.saveActivity(activity, activityDetail, crowdfundEvent, activityInput);
            return AjaxResult.success("众筹保存成功", activity.getId());
        } catch (Exception e) {
            logger.error("众筹保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 复制众筹项目视图
     *
     * @param id 编号
     * @return 交互数据
     */
    @DataControl
    @RequestMapping(value = "copyView")
    public ModelAndView copyView(@ControlParam(table = "activity", column = "member") String id) {
        ModelAndView mv = new ModelAndView("crowdfundMultiple/publishZcActNew");
        if (StringUtils.isNotEmpty(id)) {
            //活动
            Activity activity = activityService.get(id);
            ActivityOutput activityOutput = ActivityOutput.transform(activity);
            activityOutput.setEditShare(activity.getEditShare());
            activityOutput.setId(null);
            activityOutput.setCreateDate(DateUtils.getTodayDate());
            activityOutput.setUpdateDate(DateUtils.getTodayDate());
            activityOutput.setBeCrowdfundNum(0);
            activityOutput.setCrowdfundedNum(0);
            activityOutput.setJoinNum(0);
            activityOutput.setShareNum(0);
            activityOutput.setReadNum(0);
            activityOutput.setGoodNum(0);
            activityOutput.setFavorerNum(0);
            activityOutput.setRepresentNum(0);

            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
            mv.addObject("picList", picList);

            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(activity.getId(), "2");
            if (videoList.size() > 0) {
                mv.addObject("video", videoList.get(0));
            }

            //活动详情
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            mv.addObject("activityDetail", activityDetail);
            mv.addObject("activity", activityOutput);

            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            mv.addObject("crowdfundEvent", crowdfundEvent);

            List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(crowdfundEvent.getId());
            mv.addObject("eventGradations", eventGradations);
        } else {
            CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
            crowdfundEvent.setCreateBy(RealmUtils.getCurrentUser().getId());
            crowdfundEvent.setProgress(YesNoStatus.YES.getCode()); // 进行中
            List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.list(crowdfundEvent);
            mv.addObject("crowdfundEventList", crowdfundEventList);
        }
        return mv;
    }

    @RequestMapping(value = "toSendMessage")
    public ModelAndView toSendMessage(String activityId, String projectIds, String eventId) {
        ModelAndView mv = new ModelAndView("crowdfundMultiple/messageView");
        if (StringUtils.isNotEmpty(activityId)) {
            mv.addObject("targetId", activityId);
        } else if (StringUtils.isNotEmpty(eventId)) {
            mv.addObject("targetId", eventId);
        }
        mv.addObject("projectIds", projectIds);
        mv.addObject("activityId", activityId);
        mv.addObject("eventId", eventId);
        return mv;
    }

    /**
     * @param projectIds     众筹id
     * @param targetTemplate 模板
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 短信推送
     * @Date 16:41 2019/3/22
     **/
    @ResponseBody
    @RequestMapping(value = "sendAndSave")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult sendAndSave(String projectIds, String activityId, String eventId, TargetTemplate targetTemplate) {
        if (StringUtils.isEmpty(projectIds)) {
            return AjaxResult.error("众筹id不能未空");
        }
        if (StringUtils.isEmpty(targetTemplate.getTemplate())) {
            return AjaxResult.error("模板内容不能为空");
        }
        try {
            boolean isCanFlag = activityMultipleBizService.sendAndSave(projectIds, activityId, eventId, targetTemplate);
            if (!isCanFlag) {
                return AjaxResult.error("短信剩余数量不足，请先充值");
            }
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("短信推送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("短信推送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("短信发送异常");
        }
    }
}
